﻿using LpbPrj.Client.Tools.Helper;
using LpbPrj.Client.ViewModels;
using LpbPrj.Client.Views;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Media.Animation;

namespace LpbPrj.Client.Data
{
    public class GlobalData
    {
        public static void Init()
        {
            string configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");
            if (!Directory.Exists(configFilePath))
            {
                Directory.CreateDirectory(configFilePath);
            }


            ////////////////////////高质量jpg//////////////////////////////
            JpgCodecInfo = GetEncoderInfo("image/jpeg");
            MyEncoderParameters = GetEncoderParameters();
            // 获取一个Format8bppIndexed格式图像的Palette对象
            using (System.Drawing.Bitmap bmpPalette = new System.Drawing.Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format8bppIndexed))
            {
                BmpGay8Palette = bmpPalette.Palette;
            }
            for (int i = 0; i < 256; i++)
            {
                BmpGay8Palette.Entries[i] = System.Drawing.Color.FromArgb(i, i, i);
            }

            // 修改生成WriteableBitmap的索引表，从伪彩修改为灰度
            List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
            for (int i = 0; i < 256; i++)
            {
                colors.Add(System.Windows.Media.Color.FromRgb((byte)i, (byte)i, (byte)i));
            }
            BitmapGay8Palette = new System.Windows.Media.Imaging.BitmapPalette(colors);
            
        }

        public static void Save(bool softClose = false)
        {
            Config.SaveConfig(AppConfig.SavePath, softClose);
        }

        //////////////////////////////文件获取的信息和配置///////////////////////////////

        /// <summary>
        /// 基本配置，语言，皮肤
        /// </summary>
        public static AppConfig Config { get; set; } = new AppConfig();

        //////////////////////////////系统静态数据///////////////////////////////

        /// <summary>
        /// 主页面 宽度 1280/1700
        /// </summary>
        public static double MainWindowWidth { get; set; } = 1280;
        /// <summary>
        /// 主页面 高度 800/1000
        /// </summary>
        public static double MainWindowHeight { get; set; } = 800;
        /// <summary>
        /// 部分对话框页面（触摸版中和主页面大小一致的） 宽度 1280/1280
        /// </summary>
        public static double DialogWindowWidth { get; set; } = 1280;
        /// <summary>
        /// 部分对话框页面（触摸版中和主页面大小一致的） 高度 800/800
        /// </summary>
        public static double DialogWindowHeight { get; set; } = 800;
        /// <summary>
        /// 等待窗口背景透明度
        /// </summary>
        public static double BackgroundOpacity { get; set; } = 0.0;


        //保存高质量jpg文件
        public static System.Drawing.Imaging.ImageCodecInfo JpgCodecInfo { get; private set; }
        public static System.Drawing.Imaging.EncoderParameters MyEncoderParameters { get; private set; }
        /// <summary>
        /// 修改生成位图的索引表，灰度
        /// </summary>
        public static System.Drawing.Imaging.ColorPalette BmpGay8Palette { get; private set; }


        /// <summary>
        /// 修改生成WriteableBitmap的索引表，从伪彩修改为灰度
        /// </summary>
        public static System.Windows.Media.Imaging.BitmapPalette BitmapGay8Palette { get; private set; }

        /// <summary>
        /// 使用GDI+绘制A超曲线
        /// </summary>
        public static GDIPlusImage GDIPlusImage { get; private set; } = new GDIPlusImage();

        private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            int j;
            System.Drawing.Imaging.ImageCodecInfo[] encoders;
            encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }
        private static System.Drawing.Imaging.EncoderParameters GetEncoderParameters()
        {
            // for the Quality parameter category.
            // EncoderParameter object in the array.
            var myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            //设置质量 数字越大质量越好，但是到了一定程度质量就不会增加了，MSDN上没有给范围，只说是32为非负整数
            myEncoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);

            return myEncoderParameters;
        }

    }


    public static class ConfigEx
    {
        public static T LoadConfig<T>(this string savePath) where T : class, new()
        {
            T t = null;

            try
            {
                //读取Config文件夹中的配置
                if (!string.IsNullOrEmpty(savePath) && File.Exists(savePath))
                {
                    var json = FileHelper.ReadAllText(savePath).Trim();
                    if (!string.IsNullOrEmpty(json) && JsonCheck.IsJson(json))
                    {
                        t = JsonHelper.ToObject<T>(json);
                    }
                }

                //如果是不是关机保存的，读取注册表信息
                if ((t == null) || (t != null && t is ConfigBase config && !config.SoftClose))
                {
                    var json = RegHelper.RegGetValue(typeof(T).Name)?.Trim();
                    if (!string.IsNullOrEmpty(json) && JsonCheck.IsJson(json))
                    {
                        t = JsonHelper.ToObject<T>(json);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"config loading all error, {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"config loading all error, {ex.StackTrace}");
            }


            if (t == null)
            {
                t = new T();
                System.Diagnostics.Debug.WriteLine($"file not exist, {savePath}");
            }

            return t;
        }

        public static void SaveConfig<T>(this T t, string savePath, bool softClose = false) where T : class, new()
        {
            var json = JsonHelper.ToJson(t)?.Trim();
            if (t is ConfigBase config)
            {
                config.SoftClose = softClose;
                json = JsonHelper.ToJson(config)?.Trim();
            }

            if (!string.IsNullOrEmpty(json) && JsonCheck.IsJson(json) && !string.IsNullOrEmpty(savePath)) FileHelper.WriteAllText(savePath, json);

            //正常关机才使用备份文件夹进行存储
            if (!string.IsNullOrEmpty(json) && JsonCheck.IsJson(json) && softClose)
            {
                RegHelper.RegSetValue(typeof(T).Name, json);
            }
        }

    }

}